import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import {
  // 加密密钥
  key,
  // 解密密钥
  // decryptKey
} from './publickey';
import JSEncrypt from 'jsencrypt';

import {
  ElNotification,
  ElMessageBox,
  ElMessage,
  ElLoading,
} from 'element-plus';
import { getToken } from '@/utils/auth';
import errorCode from '@/utils/errorCode';
import { tansParams, blobValidate } from '@/utils/ruoyi';
import cache from '@/plugins/cache';
import useUserStore from '@/store/modules/user';
import { saveAs } from 'file-saver';

let loadingInstance: ReturnType<typeof ElLoading.service> | null = null;
const LOADING_TIME: number = 1500;
export let isRelogin = { show: false };
let authentication = '';
// 创建 axios 实例
const service = axios.create({
  baseURL: '',
  timeout: 20000,
});

// 通用方法：处理重新登录
const handleRelogin = () => {
  if (!isRelogin.show) {
    isRelogin.show = true;
    ElMessageBox.confirm(
      '登录状态已过期，您可以继续留在该页面，或者重新登录',
      '系统提示',
      {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        isRelogin.show = false;
        useUserStore()
          .logOut()
          .then(() => {
            location.href = '/index';
          });
      })
      .catch(() => {
        isRelogin.show = false;
      });
  }
  return Promise.reject('无效的会话，或者会话已过期，请重新登录。');
};

// 通用方法：错误提示
const handleErrorMessage = (
  msg: string,
  type: 'error' | 'warning' | 'info' | 'success' = 'error'
) => {
  ElMessage({
    message: msg,
    type,
  });
  return Promise.reject(new Error(msg));
};

// 通用方法：通知错误
const handleNotificationError = (msg: string) => {
  ElNotification.error({
    title: msg,
  });
  return Promise.reject('error');
};
// 加密函数
const encryptionFun = (): string | null => {
  const timer: string = String(new Date().getTime()); // 获取时间戳
  const jse = new JSEncrypt(); // 创建 JSEncrypt 实例
  jse.setPublicKey(key); // 设置公钥

  // 使用公钥加密时间戳
  const data: string | null = jse.encrypt(timer) || null;
  return data;
};

// 解密函数
// const decryptionFun = (data: string): string => {
//   const jse = new JSEncrypt(); // 创建 JSEncrypt 实例
//   jse.setPrivateKey(decryptKey); // 设置私钥
//   const timer: string = jse.decrypt(data) || ''; // 使用私钥解密
//   return timer;
// };

// 请求拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const isToken = (config.headers || {}).isToken === false;
    const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;
    const token = getToken();
    const timestamp = +new Date();
    if (token && !isToken) {
      config.headers!['token'] = token;
    }
    authentication = encryptionFun() || '';
    config.headers!['Authentication'] = authentication;
    config.headers!['Timer'] = timestamp;
    // console.log('密钥解密结果:', decryptionFun(authentication) || '');

    if (config.method === 'get' && config.params) {
      let url = config.url + '?' + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }

    if (
      !isRepeatSubmit &&
      (config.method === 'post' || config.method === 'put')
    ) {
      const requestObj = {
        url: config.url,
        data: JSON.stringify(config.data),
        time: new Date().getTime(),
      };
      const requestSize = Object.keys(JSON.stringify(requestObj)).length;
      const limitSize = 5 * 1024 * 1024;
      if (requestSize >= limitSize) {
        console.warn(
          `[${config.url}]: 请求数据大小超出允许的5M限制，无法进行防重复提交验证。`
        );
        return config;
      }

      const sessionObj = cache.session.getJSON('sessionObj');
      const interval = 1000;
      if (
        sessionObj === undefined ||
        sessionObj === null ||
        sessionObj === ''
      ) {
        cache.session.setJSON('sessionObj', requestObj);
      } else {
        const s_url = sessionObj.url; // 请求地址
        const s_data = sessionObj.data; // 请求数据
        const s_time = sessionObj.time; // 请求时间
        if (
          s_data === requestObj.data &&
          requestObj.time - s_time < interval &&
          s_url === requestObj.url
        ) {
          // 重复提交检测逻辑
        } else {
          cache.session.setJSON('sessionObj', requestObj);
        }
      }
    }
    return config;
  },
  (error) => {
    setTimeout(() => loadingInstance?.close(), LOADING_TIME);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res: AxiosResponse) => {
    setTimeout(() => loadingInstance?.close(), LOADING_TIME);

    const code = res.data.code || 200;
    const msg = res.data.msg || errorCode[code] || errorCode['default'];

    // res.request.responseType === 'blob' ||
    // res.request.responseType === 'arraybuffer'
    if (res.status === 200 && res.data.code === 20000) {
      return res.data;
    } else {
      switch (code) {
        case 401:
        case 40310:
          return handleRelogin();
        case 500:
        case 601:
          return handleErrorMessage(msg);
        case 200:
        case 20000:
          return Promise.resolve(res.data);
        case 20001:
          return Promise.resolve(res);
        case 90001:
          return Promise.resolve(res);
        case 400333:
          return Promise.resolve(res);
        case 40033:
          return Promise.resolve(res);
        case 44444:
          ElMessage({ message: msg, type: 'error' });
          return Promise.resolve(res.data);
        case 40000:
          ElMessage({ message: msg, type: 'error' });
          return Promise.reject(res);
        case 50000:
          ElMessage({ message: msg, type: 'error' });
          return Promise.reject(res);
        default:
          return handleNotificationError(msg);
      }
    }
    console.log(res, '======11');
  },
  (error) => {
    ElMessage.error('请求出错，请稍后再试');
    let { message } = error;
    if (message === 'Network Error') message = '后端接口连接异常';
    else if (message.includes('timeout')) message = '系统接口请求超时';
    else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常';
    }
    ElMessage({ message, type: 'error', duration: 5000 });
    return Promise.reject(error);
  }
);

// 通用下载方法
export function download(
  url: string,
  params: any,
  filename: string,
  config?: any
): Promise<void> {
  loadingInstance = ElLoading.service({
    text: '正在下载数据，请稍候',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  return service
    .post(url, params, {
      transformRequest: [(params) => tansParams(params)],
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob',
      ...config,
    })
    .then(async (response: AxiosResponse) => {
      const isBlob = blobValidate(response.data);
      if (isBlob) {
        const blob = new Blob([response.data]);
        saveAs(blob, filename);
      } else {
        const resText = await response.data.text();
        const rspObj = JSON.parse(resText);
        const errMsg =
          errorCode[rspObj.code] || rspObj.msg || errorCode['default'];
        ElMessage.error(errMsg);
      }
    })
    .catch((error) => {
      console.error('下载文件出错：', error);
      ElMessage.error('下载文件出现错误，请联系管理员！');
    })
    .finally(() => {
      setTimeout(() => loadingInstance?.close(), LOADING_TIME);
      loadingInstance = null;
    });
}

export default service;
